package ltd.sshine.tracking.security.entrypoint;


import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import ltd.sshine.runtime.pojo.Result;
import ltd.sshine.runtime.utils.JsonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

public class AuthenticationNologinEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
        if (e instanceof InsufficientAuthenticationException) { //没有身份验证
            resp.setStatus(HttpStatus.UNAUTHORIZED.value());
            JsonUtils.writeValue(Result.error("未登录"), resp.getOutputStream());
        } else if (e instanceof InvalidBearerTokenException) { //身份验证失败
            resp.setStatus(HttpStatus.UNAUTHORIZED.value());
            JsonUtils.writeValue(Result.error("token无效或已过期"), resp.getOutputStream());
        }
    }
}
